package com.hoshiicloud.saleorder.controller.customer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.saleorder.param.customer.GoodsBrowseRecordAddParam;
import com.hoshiicloud.saleorder.param.customer.GoodsBrowseRecordQueryParam;
import com.hoshiicloud.saleorder.service.customer.IGoodsBrowseRecordService;
import com.hoshiicloud.user.entity.customer.GoodsBrowseRecord;
import com.hoshiicloud.user.vo.customer.GoodsBrowseRecordDetailVO;
import com.hoshiicloud.user.vo.customer.GoodsBrowseRecordVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 商品浏览记录 前端控制器 浏览记录不需要修改操作
 * </p>
 *
 * @author Mr.Wu
 * @since 2019-04-28
 */
@Api(value = "前台用户操作", tags = {"商品浏览记录管理"})
@Slf4j
@Validated
@RestController
@RequestMapping("/customer/goods-browse-record")
public class GoodsBrowseRecordController {

    @Autowired
    private IGoodsBrowseRecordService goodsBrowseRecordService;

    @ApiOperation(value = "新增商品浏览记录", notes = "")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Response add(@RequestBody @Valid GoodsBrowseRecordAddParam param) {
        GoodsBrowseRecord entity = new GoodsBrowseRecord();
        BeanUtils.copyProperties(param, entity);
        // TODO 只接受指定参数
        return goodsBrowseRecordService.insert(entity);
    }

    @ApiOperation(value = "删除商品浏览记录", notes = "")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Response delete(@RequestParam String id) {
        if (StringUtils.isBlank(id)) {
            return Response.failed("id不能为空");
        }
        return goodsBrowseRecordService.deleteDataById(id);
    }

    @ApiOperation(value = "获取商品浏览记录详情", notes = "")
    @RequestMapping(value = "/getDetail", method = RequestMethod.GET)
    public Response<GoodsBrowseRecordDetailVO> getDetail(@RequestParam String id) {
        if (StringUtils.isBlank(id)) {
            return Response.failed("id不能为空");
        }
        return goodsBrowseRecordService.getDetail(id);
    }

    @ApiOperation(value = "获取商品浏览记录列表", notes = "")
    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public Response<List<GoodsBrowseRecordVO>> getList(@RequestBody @Valid GoodsBrowseRecordQueryParam param) {
        QueryWrapper<GoodsBrowseRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(param.getId() != null, GoodsBrowseRecord::getId, param.getId())
                .eq(param.getUserId() != null, GoodsBrowseRecord::getUserId, param.getUserId())
                .eq(param.getSpuId() != null, GoodsBrowseRecord::getSpuId, param.getSpuId())
                .eq(param.getChannel() != null, GoodsBrowseRecord::getChannel, param.getChannel())
                .eq(param.getStoreId() != null, GoodsBrowseRecord::getStoreId, param.getStoreId())
                .eq(param.getSkuId() != null, GoodsBrowseRecord::getSkuId, param.getSkuId());
        String key = "GoodsBrowseRecordQueryParam{" + param.toString() + "}, Page{pageNumber=" + param.getPageNumber()
                + ", pageSize=" + param.getPageSize() + "}";
        return goodsBrowseRecordService.getList(queryWrapper, key);
    }

    @ApiOperation(value = "分页查询商品浏览记录", notes = "")
    @RequestMapping(value = "/getPage", method = RequestMethod.GET)
    public Response<IPage<GoodsBrowseRecordVO>> getPage(@RequestBody @Valid GoodsBrowseRecordQueryParam param) {
        QueryWrapper<GoodsBrowseRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(param.getId() != null, GoodsBrowseRecord::getId, param.getId())
                .eq(param.getUserId() != null, GoodsBrowseRecord::getUserId, param.getUserId())
                .eq(param.getSpuId() != null, GoodsBrowseRecord::getSpuId, param.getSpuId())
                .eq(param.getChannel() != null, GoodsBrowseRecord::getChannel, param.getChannel())
                .eq(param.getStoreId() != null, GoodsBrowseRecord::getStoreId, param.getStoreId())
                .eq(param.getSkuId() != null, GoodsBrowseRecord::getSkuId, param.getSkuId());
        IPage<GoodsBrowseRecord> page = new Page<>(Long.parseLong(param.getPageNumber()),
                Long.parseLong(param.getPageSize()));
        String key =
                "GoodsBrowseRecordQueryParamToPage{" + param.toString() + "}, Page{pageNumber=" + param.getPageNumber()
                        + ", pageSize=" + param.getPageSize() + "}";
        return goodsBrowseRecordService.getPage(page, queryWrapper, key);
    }

    /**
     * 根据spuIds查询商品浏览记录
     *
     * @param spuIds 扩展spu主键集合
     * @return Response<List < Map < Long, Object>>>
     */
    @ApiOperation(value = "根据spuIds查询商品浏览记录", notes = "根据spuIds查询商品浏览记录")
    @RequestMapping(value = "getListBySpuIds", method = RequestMethod.GET)
    public Response<List<Map<String, Object>>> getListBySpuIds(@RequestParam("spuIds") List<Long> spuIds) {
        List<Map<String, Object>> result = new ArrayList<>();
        QueryWrapper<GoodsBrowseRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(CollectionUtils.isNotEmpty(spuIds) && spuIds.size() > 0, GoodsBrowseRecord::getSpuId, spuIds);
        List<GoodsBrowseRecord> list = goodsBrowseRecordService.list(queryWrapper);
        Map<Long, List<GoodsBrowseRecord>> map = list.stream()
                .collect(Collectors.groupingBy(GoodsBrowseRecord::getSpuId));
        map.keySet().forEach(item -> {
            Map<String, Object> temp = new HashMap<>(16);
            temp.put("spu_id", item);
            temp.put("count", map.get(item).size());
            result.add(temp);
        });
        return Response.data(result);
    }

    /**
     * 获取商品浏览记录根据基础spu分组
     * @return Response<List<Map<String,Object>>>
     */
    @ApiOperation(value = "获取商品浏览记录根据基础spu分组", notes = "获取商品浏览记录根据基础spu分组")
    @RequestMapping(value = "getListGroupByBaseSpuId", method = RequestMethod.GET)
    public Response<List<Map<String, Object>>> getListGroupByBaseSpuId() {
        Response<List<Map<String,Object>>> rs;
        try {
            rs = Response.data(goodsBrowseRecordService.getListGroupByBaseSpuId());
        } catch (Exception e) {
            log.error("获取商品浏览记录根据基础spu分组异常：", e.getMessage());
            rs = Response.failed("获取商品浏览记录根据基础spu分组异常："+e.getMessage());
        }
        return rs;
    }
}
